<?php
namespace app\admin\model;

use app\admin\model\Channel as ChannelModel;
use think\Db;
use think\Model;

/**
 * 后台用户模型
 * @package app\admin\model
 */
class Adminuser extends Model {
	// 设置当前模型对应的完整数据表名称
	protected $table = 'adm_user';

	// 获取注册ip
	public function setSignupIpAttr() {
		return get_client_ip(1);
	}

	/**
	 * 后台用户登录
	 * @param string $username 用户名
	 * @param string $password 密码
	 * @author amplam
	 * @return data
	 */
	//检测用户
	public function checkUser($data) {
		$info['username'] = trim($data['user']);
		// 查找用户
		$user = $this::get($info);

		if ($user['user_type'] != 'channel') {
			return ['errorCode' => 2, 'msg' => '账号不存在'];
		}
		// var_dump($user);die;
		if ($user) {
			if ($user['on_off'] == 0) {
				return ['errorCode' => 2, 'msg' => '该帐号被禁用,请联系管理员！~'];
			}
			if (md5(md5(trim($data['pwd'])) . $user['salt']) == $user['password']) {

				if ($user['user_type'] == 'channnel' && empty($user['relate_id'])) {
					return ['errorCode' => 2, 'msg' => '账号异常'];
				}
				//设置session
				session('user_id', $user['id']);
				session('username', $user['username']);
				session('user_type', $user['user_type']);
				session('relate_id', $user['relate_id']);
				session('role_id', $user['role_id']);
				session('super', $user['is_super']); //判断是否为超级管理员
				if ($user['relate_id'] != 0) {
					$channelInfo = Db::table('bus_channel')->field('company_name,level')->where(['channel_id' => $user['relate_id']])->find();
					session('channel_name', $channelInfo['company_name']);
					session('channel_level', $channelInfo['level']);
				}
				//查询用户对应的权限信息
				$a = $this->getUserAuth($user['role_id']);

				// halt($a);
				return ['errorCode' => 0, 'msg' => '登录成功', 'url' => url('Index/index')];
			} else {
				//密码错误
				return ['errorCode' => 2, 'msg' => '帐号或密码错误'];
			}
		} else {
			//用户名不存在
			return ['errorCode' => 2, 'msg' => '帐号或密码错误'];
		}
	}

	/**
	 * 用户开启与关闭
	 * @return res
	 */
	public function updateOnOffOne($userid, $state) {
		$user = new Adminuser;
		trace(session('username') . '把用户id为' . $userid . '的开启状态改为了' . $state, 'info');
		return $user->isUpdate(true)->save(['on_off' => $state], ['id' => $userid]);
	}

	/**
	 * 添加一条用户信息
	 */
	public function saveUserOne($data) {
		//实例化
		$user = new Adminuser;
		$salt = uniqid();

		if (Adminuser::get(['username' => $data['admin_name']])) {
			return '2';
		}

		//角色分配
		if ($data['type'] == 'channel') {
			if ($data['role'] != 52) //52放行
			{
				$level = ChannelModel::where('channel_id', $data['admin_relate'])->value('level');

				switch ($level) {
				case '1':
					$data['role'] = 49;
					break;
				case '2':
					$data['role'] = 50;
					break;
				case '3':
					$data['role'] = 51;
					break;
				case '4':
					$data['role'] = 50;
					break;
				case '5':
					$data['role'] = 51;
					break;

				default:
					return '0';
					break;
				}
			}
		}

		$user->username    = trim($data['admin_name']);
		$user->password    = md5(md5($data['password']) . $salt);
		$user->on_off      = trim($data['onoff']);
		$user->salt        = $salt;
		$user->user_type   = trim($data['type']);
		$user->role_id     = trim($data['role']);
		$user->mark_up     = $data['mark'];
		$user->relate_id   = trim($data['admin_relate']);
		$user->create_user = session('username');
		try {
			$user->isUpdate(false)->save();
			if ($user) {
				return '1';
			} else {
				return '0';
			}
		} catch (Exception $e) {
			return '0';
		}
	}

	/**
	 * 查询用户对应的权限信息
	 * @param  intger $roleId 用户的角色ID
	 */
	// private
	public function getUserAuth($roleId) {
		if (session('user_type') == 'channel') {
			//等级分权限
			switch (session('channel_level')) {
			case 1:
				$roleId = 49;
				break;
			case 2:
				$roleId = 50;
				break;
			case 3:
				$roleId = 51;
				break;
			case 4:
				$roleId = 50;
				break;
			case 5:
				$roleId = 51;
				break;

			default:
				session('auth', []);
				session('menu', []);
				return;
				break;
			}
		} else {

		}
		// 1. 根据角色ID查询role_auth_list（权限ID字符串）
		$info = Db::table("adm_role")->field('role_auth_list')->find($roleId); // 注意：role_auth_list *
		if ($info['role_auth_list'] == '*') {

			//视频平台的权限分开
			if (isMmsOrSms() && session('user_id') == 1) {
				$info = Db::table("adm_role")->field('role_auth_list')->find(56);

				GOTO ELSIF;
			}
			// 超级管理员 拥有所有的权限
			session('auth', '*');
			// 超级管理员的权限菜单应该是不受限制 后台左侧的菜单一般只显示两级菜单
			// 顶级菜单 auth_pid = 0
			$menu = Db::table("adm_auth")->where('auth_pid = 0')->order('order_num , auth_id ')->select(); // [['auth_id' => 1, 'auth_pid' => 0, 'sub' => [[],[]]],[]]
			// 顶级下面的二级权限
			foreach ($menu as $k => $v) {
				// 二级 条件 放：对应的顶级菜单对应的这项里面
				$menu[$k]['sub'] = Db::table("adm_auth")->where("auth_pid", $v['auth_id'])->order('order_num , auth_id ')->select();
			}
			session('menu', $menu);

		} elseif ($info['role_auth_list'] != '') {

			ELSIF:

			// 普通角色 存在对应的权限 $info['role_auth_list'];
			// 数据：二维数组 到时候做权限的验证  in_array( CONTROLLER_NAME .'/'. ACTION_NAME, 用户的权限一维数组)
			$_authData = Db::table("adm_auth")->field('auth_id,auth_name,auth_c_a,auth_pid,menu_icon')->where("auth_id in (" . $info['role_auth_list'] . ")")->order('order_num , auth_id ')->select();
			$menu      = array();
			// 转换：
			$authData = array();
			foreach ($_authData as $k => $v) {
				// 顶级权限
				if ($v['auth_pid'] == 0) {
					$menu[] = $v;
				}
				$authData[] = $v['auth_c_a']; // ['User/lst', 'User/add', 'Order/add'];
			}
			// 二级权限信息
			foreach ($menu as $k => $v) {
				foreach ($_authData as $key => $value) {
					if ($value['auth_pid'] == $v['auth_id']) {
						// 每一个顶级权限可能存在多个子级
						$menu[$k]['sub'][] = $value;
					}
				}
			}
			// 保存起来
			session('auth', $authData);
			session('menu', $menu);
		} else {
			$authData = [];
			$menu     = [];
			session('auth', $authData);
			session('menu', $menu);
		}
	}

	//检测用户存不存在,存在修改密码
	public function checkUserInfo($data) {
		$info['id'] = trim($data['user_id']);
		$user       = $this::get($info);
		if ($user) {
			if (md5(md5(trim($data['password'])) . $user['salt']) == $user['password']) {

				$salt = uniqid();

				$new_pwd = md5(md5(trim($data['password2'])) . $salt);

				$s = $user->save(['password' => $new_pwd, 'salt' => $salt]);

				return $s;
			}

		} else {
			return 0;
		}
	}

	//渠道添加登录用户
	public function channelAdd($data) {
		//实例化
		$user = new Adminuser;
		$salt = uniqid();

		if (Adminuser::get(['username' => $data['admin_name']])) {
			return '2';
		}
		$level = ChannelModel::where('channel_id', $data['admin_relate'])->value('level');

		if ($level) {
			$user->username  = trim($data['admin_name']);
			$user->password  = md5(md5($data['password']) . $salt);
			$user->on_off    = trim($data['onoff']);
			$user->salt      = $salt;
			$user->user_type = 'channel';
			$user->role_id   = 51;

			// if ($data['role_level'] == 1) {
			// 	switch ($level) {
			// 	case '2':
			// 		$user->role_id = 50;
			// 		break;
			// 	case '3':
			// 		$user->role_id = 51;
			// 		break;
			// 	case '5':
			// 		$user->role_id = 51;
			// 		break;

			// 	default:
			// 		# code...
			// 		break;
			// 	}
			// } else {
			// 	$user->role_id = 52;
			// }

			$user->mark_up     = $data['mark'];
			$user->relate_id   = trim($data['admin_relate']);
			$user->create_user = session('username');
			try {
				$user->isUpdate(false)->save();
				if ($user) {
					return '1';
				} else {
					return '0';
				}
			} catch (Exception $e) {
				return '0';
			}
		}

		return '0';
	}
}
